package com.ds.infrastructure.hyperspace.container.admin.processor;

import com.ds.infrastructure.hyperspace.common.admin.AdminResponseVO;
import com.ds.infrastructure.hyperspace.common.config.ContainerConfig;
import com.ds.infrastructure.hyperspace.common.config.EndpointsConfig;
import com.ds.infrastructure.hyperspace.common.config.PipelineConfig;
import com.ds.infrastructure.hyperspace.container.internal.NettyContainer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;

/**
 * @author  Weishaoying
 * @date 2019/6/26 下午4:37
 */
@Slf4j
public class ApplyConfigProcessor implements Processor {

    @Override
    public AdminResponseVO process(NettyContainer container, byte[] msg) throws IOException {
        if (msg == null || msg.length < 1) {
            log.error("Config Data is empty!");
            return AdminResponseVO.error("Config data is empty");
        }
        ContainerConfig containerConfig = NettyContainer.OBJECT_MAPPER.readValue(msg, ContainerConfig.class);
        List<PipelineConfig> pipelineList = containerConfig.getPipelines();
        EndpointsConfig endpointsConfig = containerConfig.getEndpoints();
        if (endpointsConfig == null || CollectionUtils.isEmpty(pipelineList)) {
            log.error("Console config invalid, endpoint or pipeline not found!");
            return AdminResponseVO.error("Console config invalid, endpoint or pipeline not found!");
        }
        container.getMetricsManager().containerConfigVersionGauge(containerConfig.getVersion());
        List<String> errorLog = container.initEndpointAndPipeline(endpointsConfig, pipelineList);
        if (!errorLog.isEmpty()) {
            return AdminResponseVO.error(errorLog.toString());
        }
        return AdminResponseVO.OK;
    }

}
